<template>
  <div class="login register">
    <LoginLeftView></LoginLeftView>
    <div class="right-wrap">
      <div class="header">
        <ArtLogo class="icon" />
        <h1>{{ systemName }}</h1>
      </div>
      <div class="login-wrap">
        <div class="form">
          <div class="form-item">
            <!-- <h3 class="title">{{ $t('register.title') }}</h3> -->
            <h3 class="sub-title">{{ $t('register.title') }}</h3>
            <!-- <p class="sub-title">{{ $t('register.subTitle') }}</p> -->
            <ElForm ref="formRef" :model="formData" :rules="rules" label-position="top">
              <ElFormItem prop="username">
                <ElInput v-model.trim="formData.username" :placeholder="$t('register.placeholder[0]')" />
              </ElFormItem>

              <ElFormItem prop="phone">
                <ElInput v-model.trim="formData.phone" :placeholder="$t('register.placeholder[3]')" />
              </ElFormItem>
              <ElFormItem prop="code">
                <el-row :gutter="12" style="width: 100%">
                  <el-col :span="countdown > 0 ? 17 : 18">
                    <ElInput v-model="formData.code" :placeholder="$t('login.placeholder[4]')" @blur="blur" />
                  </el-col>
                  <el-col :span="countdown > 0 ? 7 : 6">
                    <el-button size="large" class="code" @click="sendSmsCodeData">
                      {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
                    </el-button>
                  </el-col>
                </el-row>
              </ElFormItem>
              <!-- 
              <ElFormItem prop="password">
                <ElInput v-model.trim="formData.password" :placeholder="$t('register.placeholder[1]')" type="password"
                  autocomplete="off" />
              </ElFormItem> -->
              <ElFormItem prop="password">
                <ElInput :placeholder="$t('login.placeholder[1]')" v-model.trim="formData.password" size="large"
                  :type="showPassword ? 'text' : 'password'" radius="8px" autocomplete="off">
                  <template #suffix>
                    <el-button @click="showPassword = !showPassword" type="text" style="padding: 0 6px;" tabindex="-1">
                      <el-icon>
                        <template v-if="showPassword">
                          <View style="color: #606266;" />
                        </template>
                        <template v-else>
                          <Hide style="color: #606266;" />
                        </template>
                      </el-icon>
                    </el-button>
                  </template>
                </ElInput>
              </ElFormItem>

              <!-- <ElFormItem prop="confirmPassword">
                <ElInput v-model.trim="formData.confirmPassword" :placeholder="$t('register.placeholder[2]')"
                  type="password" autocomplete="off" @keyup.enter="register" />
              </ElFormItem> -->
              <ElFormItem prop="confirmPassword">
                <ElInput :placeholder="$t('login.placeholder[5]')" v-model.trim="formData.confirmPassword" size="large"
                  :type="showConfirmPassword ? 'text' : 'password'" radius="8px" autocomplete="off">
                  <template #suffix>
                    <el-button @click="showConfirmPassword = !showConfirmPassword" type="text" style="padding: 0 6px;"
                      tabindex="-1">
                      <el-icon>
                        <template v-if="showConfirmPassword">
                          <View style="color: #606266;" />
                        </template>
                        <template v-else>
                          <Hide style="color: #606266;" />
                        </template>
                      </el-icon>
                    </el-button>
                  </template>
                </ElInput>
              </ElFormItem>
              <ElFormItem prop="promoterCode">
                <ElInput v-model.trim="formData.promoterCode" :placeholder="$t('login.placeholder[7]')"
                  :disabled="invitationCode ? true : false" size="large" radius="8px" autocomplete="off" />
              </ElFormItem>

              <ElFormItem prop="agreement">
                <ElCheckbox v-model="formData.agreement">
                  <span class="agreement-text">
                    我已阅读并同意
                  </span>
                  <span style="color: var(--main-color); text-decoration: none" @click.stop="toPrivacy">《平台使用协议》</span>
                  <span class="agreement-text">和</span>
                  <span style="color: var(--main-color); text-decoration: none" @click.stop="toCharge">《隐私政策》</span>
                </ElCheckbox>
              </ElFormItem>

              <div style="margin-top: 15px">
                <ElButton class="register-btn" type="primary" @click="register" :loading="loading" v-ripple>
                  {{ $t('register.submitBtnText') }}
                </ElButton>
              </div>

              <div class="footer">
                <p>
                  {{ $t('register.hasAccount') }}
                  <router-link :to="RoutesAlias.Login">{{ $t('register.toLogin') }}</router-link>
                </p>
              </div>
            </ElForm>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import AppConfig from '@/config'
import { RoutesAlias } from '@/router/routesAlias'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { UserService } from '@/api/usersApi'
import { useI18n } from 'vue-i18n'
import { LoginMethod } from '@/api/LoginMethod'
import { useRouter, useRoute } from 'vue-router'
const route = useRoute();

defineOptions({ name: 'Register' })

const { t } = useI18n()

const router = useRouter()
const formRef = ref<FormInstance>()

const systemName = AppConfig.systemInfo.name
const loading = ref(false)
const countdown = ref(0)
const showPassword = ref(false)
const showConfirmPassword = ref(false)

const formData = reactive({
  phone: '',
  code: '',
  username: '',
  password: '',
  confirmPassword: '',
  agreement: true,
  promoterCode: ''
})

const canSend = computed(() => {
  return formData.phone && /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(formData.phone)
})

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error(t('register.placeholder[1]')))
  } else {
    if (formData.confirmPassword !== '') {
      formRef.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error(t('register.rule[0]')))
  } else if (value !== formData.password) {
    callback(new Error(t('register.rule[1]')))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  phone: [{ required: true, message: t('register.rule[5]'), trigger: 'blur' }],
  username: [{ required: true, message: t('register.rule[6]'), trigger: 'blur' }],
  code: [
    { required: true, message: t('register.rule[7]'), trigger: 'blur' },
    { pattern: /^\d{6}$/, message: t('register.rule[8]'), trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, message: t('register.rule[3]'), trigger: 'blur' }
  ],
  confirmPassword: [{ required: true, validator: validatePass2, trigger: 'blur' }],
  agreement: [
    {
      validator: (rule: any, value: boolean, callback: any) => {
        if (!value) {
          callback(new Error(t('register.rule[4]')))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})

const register = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          loading.value = true
          const { code, data, msg } = await UserService.register({
            username: formData.username,
            password: formData.password,
            contactPerson: formData.phone,
            promoterCode: formData.promoterCode
          })
          if (code === '00000') {
            if (data.status === 2) {
              ElMessage.success(t('register.tip1'))
            } else if (data.status === 1) {
              ElMessage.success(t('register.tip2'))
            }
            toLogin()
          } else {
            ElMessage.error(msg)
          }
        } catch (e) {
        } finally {
          loading.value = false
        }
      }
    })
  } catch (error) {
    console.log('验证失败', error)
  }
}

const toLogin = () => {
  setTimeout(() => {
    router.push(RoutesAlias.Login)
  }, 1000)
}

const toPrivacy = () => {
  // 如果被路由守卫拦截，直接跳转到新页面
  const routeData = router.resolve({ name: 'PrivacyProtocol' })
  if (routeData) {
    window.open(routeData.href, '_blank')
  } else {
    // 路由守卫拦截时，手动拼接url跳转
    window.open('/termsConditions/privacy', '_blank')
  }
}

const toCharge = () => {
  // 如果被路由守卫拦截，直接跳转到新页面
  const routeData = router.resolve({ name: 'ChargeProtocol' })
  if (routeData) {
    window.open(routeData.href, '_blank')
  } else {
    // 路由守卫拦截时，手动拼接url跳转
    window.open('/termsConditions/charge', '_blank')
  }
}

async function sendSmsCodeData() {
  try {
    if (!formData.phone) {
      ElMessage.error('请输入手机号')
      return
    }
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    const paramsObj = {
      mobile: formData.phone,
      tempId: 2407765,
      type: 2
    }
    const { code, msg } = await LoginMethod.sendSmsCode(paramsObj)
    if (code === '00000') {
      // await handleSubmit()
      ElMessage.success('验证码已发送')
    } else {
      ElMessage.error(msg)
    }
  } catch (e) {
  } finally {
  }
}

const blur = async () => {
  if (formData.phone && formData.code && formData.code.length === 6) {
    const res = await LoginMethod.verification({
      mobile: formData.phone,
      code: formData.code
    })
    if (res.code !== '00000') {
      formData.code = ''
      ElMessage.error('验证码错误')
    }
  }
}

const invitationCode = ref<any>('')

onMounted(() => {
  invitationCode.value = route.query.code;
  if (invitationCode.value) {
    formData.promoterCode = invitationCode.value
  }
  console.log('Code:', invitationCode.value); // 输出: Rgzs5oDqqS2AT3
});
</script>

<style lang="scss" scoped>
@use '../login/index' as login;
@use './index' as register;

.agreement-text {
  color: #333;
}
</style>
